/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.framework.cms.study.controller;

import java.sql.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.luence.domain.LuceneDocument;
import com.seeyoui.kensite.framework.luence.util.LuceneUtils;
import com.seeyoui.kensite.framework.system.domain.SysUser;
import com.seeyoui.kensite.framework.system.util.UserUtils;
import com.seeyoui.kensite.framework.cms.article.service.ArticleService;
import com.seeyoui.kensite.framework.cms.study.domain.Study;
import com.seeyoui.kensite.framework.cms.study.service.StudyService;
/**
 * Study
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-12
 */

@Controller
@RequestMapping(value = "cms/study")
public class StudyController extends BaseController {
	
	@Autowired
	private StudyService studyService;
	@Autowired
	private ArticleService ArticleService;
	
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("framework/cms/study/"+page, modelMap);
	}
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		Study study = studyService.findOne(id);
		return study;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Study study = studyService.findOne(id);
		modelMap.put("study", study);
		return new ModelAndView("framework/cms/study/"+page, modelMap);
	}
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		List<Study> studyList = studyService.findList(study);
		int total = studyService.findTotal(study);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(studyList);
		return eudg;
	}
	
	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:view")
	@RequestMapping(value = "/list/page", method=RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		List<Study> studyList = studyService.findList(study);
		int total = studyService.findTotal(study);
		Page<Study> page = new Page<Study>(study.getPage(), study.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", studyList);
		dataMap.put("page", page);
		return dataMap;
	}
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		List<Study> studyList = studyService.findAll(study);
		return studyList;
	}
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		if (!beanValidator(modelMap, study)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		studyService.save(study);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		if (!beanValidator(modelMap, study)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		studyService.update(study);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param studyId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		studyService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		studyService.remove(study);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param study
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("cms:study:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Study study) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Study> studyList = studyService.findAll(study);
		new ExportExcel(null, Study.class).setDataList(studyList).write(response, fileName).dispose();
		return null;
	}
	
	/**
	 * 学习记录列表接口
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/listMyStudy", method=RequestMethod.POST)
	@ResponseBody
	public Result listMyStudy(HttpServletRequest request){
		String userId = UserUtils.getUser(request).getId();
		if (StringUtils.isEmpty(userId)) {
			return Result.failure("用户不存在");
		}
		
		List<Study> studyList = studyService.findStudyByUserId(userId);
		if (studyList.isEmpty()) {
			return Result.failure("查询失败");
		} else {
			return Result.success(studyList);
		}
	}
	
	/**
	 * 每分钟接收客户端发来的时间记录
	 * @param request
	 * @param articleId
	 * @return
	 */
	@RequestMapping("/addStudyTime")
	@ResponseBody
	public String addStudyTime(HttpServletRequest request,String articleId){
		SysUser sysUser = UserUtils.getUser(request);
		Study study = studyService.findStudyByUserIdAndArticleId(sysUser.getId(), articleId);
		if(study == null){
			Study newStudy = new Study();
			newStudy.setUserId(sysUser.getId());
			newStudy.setArticleId(articleId);
			newStudy.setDuration("1");
			studyService.save(newStudy);
		}else{
			String maxDuration = ArticleService.findOne(articleId).getMaxDuration();
			String minDuration = ArticleService.findOne(articleId).getMinDuration();
			int maxTime = Integer.parseInt(maxDuration);
			int minTime = Integer.parseInt(minDuration);
			if(StringUtils.isEmpty(study.getPoint())){
				if(Integer.parseInt(study.getDuration()) < maxTime){
					int newTime = Integer.parseInt(study.getDuration()) + 1;
					study.setDuration(String.valueOf(newTime));
					studyService.update(study);
				}
				if(Integer.parseInt(study.getDuration()) > minTime){
					String point = ArticleService.findOne(articleId).getPoint();
					study.setPoint(point);
					studyService.update(study);
				}
			}else{
				if(Integer.parseInt(study.getDuration()) < maxTime){
					int newTime = Integer.parseInt(study.getDuration()) + 1;
					study.setDuration(String.valueOf(newTime));
					studyService.update(study);
				}
			}
		}
		return "";
	}
	
}